<template>
  <div class="update-photo-container">
    <img class="image" :src="image" ref="image">
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '../../api/profile'

export default {
  name: 'updatePhoto',
  props: {
    file: {
      required: true
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null // 裁切器实例
    }
  },
  created () {
    // 在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图
  },
  mounted () {
    // 在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
    const image = this.$refs.image // 获取需要裁切的图片 DOM
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file)
        })
      })
    },
    async onConfirm () {
      this.$toast.loading({
        message: '更新中……',
        forbidClick: true,
        duration: 0 // 展示时间，0 表示持续展示
      })
      const file = await this.getCroppedCanvas()
      // 如果要求 Content-Type 是 multipart/form-data，则一定要提交 FormData 数据对象，专门用于文件上传的，不能提交 {}
      const fd = new FormData()
      // fd.append('photo', this.file)
      fd.append('photo', file)
      await updateUserPhoto(fd)
      this.$emit('close')
      this.$emit('update-photo', this.image)
      this.$toast.success('更新成功！')
    }
  }
}
</script>

<style scoped>
.update-photo-container {
  height: 100%;
}
。image {
  display: block;
  max-width: 100%;
}
.van-nav-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
/deep/ .van-nav-bar span {color: #FFF;}
</style>
